/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.peng.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.peng.domain.RecyclerReserve;
import me.peng.domain.RecyclerUser;
import me.peng.domain.RecyclercdsRecord;
import me.peng.domain.config.SysResult;
import me.peng.domain.mapper.DsRecordMapper;
import me.peng.domain.mapper.RecyclerUserMpper;
import me.peng.domain.mapper.UserReserveMapper;
import me.peng.utils.ValidationUtil;
import me.peng.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.peng.repository.RecyclerReserveRepository;
import me.peng.service.RecyclerReserveService;
import me.peng.service.dto.RecyclerReserveDto;
import me.peng.service.dto.RecyclerReserveQueryCriteria;
import me.peng.service.mapstruct.RecyclerReserveMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.peng.utils.PageUtil;
import me.peng.utils.QueryHelp;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author pengjianye
* @date 2021-09-30
**/
@Service
@RequiredArgsConstructor
public class RecyclerReserveServiceImpl implements RecyclerReserveService {

    private final RecyclerReserveRepository recyclerReserveRepository;
    private final RecyclerReserveMapper recyclerReserveMapper;

    @Autowired
    UserReserveMapper reserveMapper;
    @Override
    public Map<String,Object> queryAll(RecyclerReserveQueryCriteria criteria, Pageable pageable){
        Page<RecyclerReserve> page = recyclerReserveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(recyclerReserveMapper::toDto));
    }

    @Override
    public List<RecyclerReserveDto> queryAll(RecyclerReserveQueryCriteria criteria){
        return recyclerReserveMapper.toDto(recyclerReserveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public RecyclerReserveDto findById(Integer id) {
        RecyclerReserve recyclerReserve = recyclerReserveRepository.findById(id).orElseGet(RecyclerReserve::new);
        ValidationUtil.isNull(recyclerReserve.getId(),"RecyclerReserve","id",id);
        return recyclerReserveMapper.toDto(recyclerReserve);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecyclerReserveDto create(RecyclerReserve resources) {
        return recyclerReserveMapper.toDto(recyclerReserveRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RecyclerReserve resources) {

        if ("已完成".equals(resources.getOrderStatus())&& "已取件".equals(resources.getReserveStatus())){
            addCreadits(resources.getId());
        }
        RecyclerReserve recyclerReserve = recyclerReserveRepository.findById(resources.getId()).orElseGet(RecyclerReserve::new);
        ValidationUtil.isNull( recyclerReserve.getId(),"RecyclerReserve","id",resources.getId());
        recyclerReserve.copy(resources);
        recyclerReserveRepository.save(recyclerReserve);


    }


    //添加积分
    private void addCreadits(int id) {
        //获取订单信息
       RecyclerReserve recyclerReserve=reserveMapper.selectById(id);
       //获取用户id
        Integer parentId =recyclerReserve.getParentId();
        //获取重量
        String weght=recyclerReserve.getWeight();

        //根据重量增加积分
        String s1=weght.toLowerCase().replace("kg","");
        int weghtint=Integer.parseInt(s1);
        System.out.println("积分值:------------------------------->"+weghtint);

        if (weghtint==5){
            addreadit(20,parentId );
        }else if (weghtint<5){
            addreadit(10,parentId );
        }else{
           int wgt=20*(weghtint/5);
           addreadit(wgt,parentId );
        }

    }

    @Autowired
    RecyclerUserMpper userReserveMapper;
    private void addreadit(int weght,int paretId) {


        //先查询当前得积分值
        RecyclerUser recyclerUser2 =userReserveMapper.selectById(paretId);
        int point=recyclerUser2.getPoint();

        //配置积分值
        RecyclerUser recyclerUser=new RecyclerUser();
        //加上原有的积分
        int sunpoint=weght+point;
        recyclerUser.setId(paretId).setPoint(sunpoint);
        //更新用户积分
        userReserveMapper.updateById(recyclerUser);

        //插入积分记录
         RecyclercdsRecord recyclercdsRecord= new RecyclercdsRecord();
         recyclercdsRecord.setParentId(paretId);
         recyclercdsRecord.setUname(recyclerUser2.getUsername());
         recyclercdsRecord.setRtitle("积分任务");
         recyclercdsRecord.setType("积分");
         recyclercdsRecord.setCoreditnum("+"+weght);
        Date date = new Date();
        recyclercdsRecord.setCreatedate(new Timestamp(date.getTime()));
        postInsideCreditsRecord(recyclercdsRecord);

    }

    /**
     * 积分记录
     */

    @Autowired
    DsRecordMapper dsRecordMapper;
    public void postInsideCreditsRecord(RecyclercdsRecord recyclercdsRecord) {

        dsRecordMapper.insert(recyclercdsRecord);
        System.out.println("RecyclerReserveServicelImpl/postInsideCreditsRecord------------------------------------------>积分记录插入成功");

    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            recyclerReserveRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RecyclerReserveDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RecyclerReserveDto recyclerReserve : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("关联编号", recyclerReserve.getParentId());
            map.put("订单编号", recyclerReserve.getOrderNumber());
            map.put("订单状态", recyclerReserve.getOrderStatus());
            map.put("预约状态", recyclerReserve.getReserveStatus());
            map.put("重量", recyclerReserve.getWeight());
            map.put("预约时间", recyclerReserve.getReserveTime());
            map.put("下单时间", recyclerReserve.getPlaceTime());
            map.put("地址ID", recyclerReserve.getAddressid());
            map.put("订单地址信息", recyclerReserve.getOrderinfo());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }



    /**
     * recyclerReserve  提交订单
     * @param recyclerReserve
     * @return
     */
    @Override
    public SysResult postOrderInfo(RecyclerReserve recyclerReserve) {
        reserveMapper.insert(recyclerReserve);
        return SysResult.success();
    }

    /**
     * 查询订单信息
     * @return
     */
    @Override
    public SysResult getOrderInfo(Integer paretId) {
        QueryWrapper<RecyclerReserve> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",paretId);
        List<RecyclerReserve> list=reserveMapper.selectList(queryWrapper);
        return SysResult.success(list);
    }

    /**
     * 删除用户订单
     * @param id
     * @return
     */
    @Override
    public SysResult deleteOrderInfo(Integer id) {

        reserveMapper.deleteById(id);

        return SysResult.success();
    }

    @Override
    public SysResult putOrderInfo(RecyclerReserve recyclerReserve) {
        reserveMapper.updateById(recyclerReserve);
        return SysResult.success();
    }
}
